package com.rabbitmq.workfair;

import com.rabbitmq.client.*;
import com.rabbitmq.util.ConnectionUtil;
import lombok.SneakyThrows;

import java.io.IOException;

public class Recv1 {
    private static String queue_name = "simple_name";
    @SneakyThrows
    public static void main(String[] args) {
        //1、获得连接
        Connection connection = ConnectionUtil.getConnection();
        //2、创建通道
        Channel channel = connection.createChannel();
        //3、申明一个队列
        channel.queueDeclare(queue_name,false,false,false,null);

        //一次给我推送一条消息
        channel.basicQos(1);

        //4、获得数据
        Consumer consumer = new DefaultConsumer(channel){

            @SneakyThrows
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //在这里处理业务
                String message = new String(body);
                System.out.println("接收到的数据：" + message);
                Thread.sleep(1000);

                //打开手动应答
                //void basicAck(long deliveryTag, boolean multiple) throws IOException;
                //deliveryTag:发货 发送标签
                //multiple:true 批量通知服务端RabbitMQ我处理完成了
                //multiple:false 只是告诉服务端RabbitMQ我当前处理完成了
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        //关闭自动应答:告诉服务端我处理完成了
        boolean autoAck = false;//通知RabbitMQ服务端 我这里处理完消息了
        //5、处理消费端数据
        channel.basicConsume(queue_name,autoAck,consumer);

        //后面不需要关闭连接、通道 就一直启动状态 待接收数据
    }
}
